<template>
  <div>
    <el-tree
      ref="tree"
      show-checkbox
      default-expand-all
      check-strictly
      :data="list"
      :props="{label:'name'}"
      node-key="id"
    />
    <div style="margin-top: 20px; text-align: right;">
      <el-button type="primary" @click="hSubmit">确定</el-button>
      <el-button @click="hCancel">取消</el-button>
    </div>
  </div>
</template>

<script>
import { getPermissionList } from '@/api/permissions'
import { tranListToTreeList } from '@/utils'
import { assignPrem, getRolesDetail } from '@/api/settings'
export default {
  props: {
    roleId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      list: []
    }
  },
  created() {
    this.loadPermissionList()
  },
  methods: {
    async hSubmit() {
      try {
        const permIds = this.$refs.tree.getCheckedKeys()
        const res = await assignPrem({ id: this.roleId, permIds: permIds })
        console.log('', res)
        // 保存数据
        this.$emit('success')
      } catch (err) {
        console.log('', err)
      }
    },
    // 获取权限的数据转化为树形的数据,在树形组建中显示
    async loadPermissionList() {
      try {
        const res = await getPermissionList()
        console.log('loadPermissionList', res)
        const perIds = await getRolesDetail(this.roleId)
        console.log(perIds, 'perIds')
        // 使用setCheckedKeys选中角色所拥有的的权限点
        this.$refs.tree.setCheckedKeys(perIds.data.permIds)
        // 保存数据
        this.list = tranListToTreeList(res.data)
      } catch (err) {
        console.log('loadPermissionList', err)
      }
    },
    hCancel() {
    // 通过父组件去关闭弹层
      this.$emit('success')
    }
  }
}
</script>

<style>

</style>
